
package com.crowdfunding.circle.analyze.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crowdfunding.circle.analyze.dao.AnalyzeItemDao;
import com.crowdfunding.circle.analyze.dao.ProjectAnalyzeDao;
import com.crowdfunding.circle.analyze.dao.ProjectTypeDao;
import com.crowdfunding.circle.analyze.entity.AnalyzeItemVO;
import com.crowdfunding.circle.analyze.entity.ProjectAnalyzeVO;
import com.crowdfunding.circle.analyze.entity.ProjectTypeVO;
import com.crowdfunding.circle.analyze.param.ProjectAnalyzeParam;
import com.crowdfunding.circle.project.dao.ProjectDao;
import com.crowdfunding.circle.project.entity.ProjectVO;

/**
 * 拆解报告Service实现类
 *
 * @author 朱国军
 * @version 2016年07月03日 朱国军
 */
@Service
public class ProjectAnalyzeService {
    
    @Autowired
    private ProjectAnalyzeDao projectAnalyzeDao;
    
    @Autowired
    private AnalyzeItemDao analyzeItemDao;
    
    @Autowired
    private ProjectTypeDao projectTypeDao;

    @Autowired
    private ProjectDao projectDao;
    
    public Map<String, Object> getDataForInsert(Integer platformType, String projectId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ProjectAnalyzeVO analyzeVO = new ProjectAnalyzeVO();
        ProjectTypeVO projectTypeVO = new ProjectTypeVO();
        
        if (StringUtils.isNotBlank(projectId)) {
            ProjectVO projectVO = projectDao.findById(projectId);
            analyzeVO.setPlatformType(projectVO.getPlatformType());
            analyzeVO.setPlatformAddress(projectVO.getPlatformAddress());
            analyzeVO.setPlatformCity(projectVO.getPlatformCity());
            analyzeVO.setPlatformProvince(projectVO.getPlatformProvince());
            analyzeVO.setPlatformName(projectVO.getPlatformName());
            analyzeVO.setProjectName(projectVO.getProjectName());
            analyzeVO.setPlatformUrl(projectVO.getPlatformUrl());
            projectTypeVO = projectTypeDao.findByTypeIndex(projectVO.getPlatformType());
            
            analyzeVO.setProjectTypeId(projectTypeVO.getProjectTypeId());
        } else {
            projectTypeVO = projectTypeDao.findByTypeIndex(platformType);
            analyzeVO.setPlatformType(platformType);
            analyzeVO.setProjectTypeId(projectTypeVO.getProjectTypeId());
        }
        resultMap.put("analyze", analyzeVO);
        resultMap.put("projectType", projectTypeVO);
        
        List<AnalyzeItemVO> analyzeItemList = analyzeItemDao.queryListByTypeId(projectTypeVO.getProjectTypeId(), null);

        resultMap.put("analyzeItemList", analyzeItemList);
        
        return resultMap;
    }

    public Map<String, Object> getDataForUpdate(String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ProjectAnalyzeVO analyzeVO = projectAnalyzeDao.findById(id);

        ProjectTypeVO projectTypeVO = projectTypeDao.findByTypeIndex(analyzeVO.getPlatformType());
        
        resultMap.put("analyze", analyzeVO);

        resultMap.put("projectType", projectTypeVO);
        
        List<AnalyzeItemVO> analyzeItemList = analyzeItemDao.queryListByTypeId(projectTypeVO.getProjectTypeId(), id);

        resultMap.put("analyzeItemList", analyzeItemList);
        return resultMap;
    }
    
    /**
     * 修改或新增
     *
     * @param entity 要修改的拆解报告对象
     * @return 返回修改的条数
     */
    public Integer update(ProjectAnalyzeVO analyze, String userId, HttpServletRequest request) {
        Integer affectCount = 0;
        String projectAnalyzeId = "";
        if (analyze != null && StringUtils.isNotBlank(analyze.getProjectAnalyzeId())) {
            projectAnalyzeId = analyze.getProjectAnalyzeId();
        } else if (analyze != null) {
            projectAnalyzeId = UUID.randomUUID().toString();
            analyze.setPublishUser(userId);
            analyze.setDataStatus(0);
        }
        
        int chargeResult = updateAnalyzeItem(projectAnalyzeId, analyze.getProjectTypeId(), userId, request);
        if (chargeResult == 4) {
            throw new RuntimeException("请至少填写一项拆解内容");
        } else {
            analyze.setChargeState(chargeResult);
        }
        
        if (analyze != null && StringUtils.isNotBlank(analyze.getProjectAnalyzeId())) {
            affectCount = projectAnalyzeDao.update(analyze);
        } else if (analyze != null) {
            analyze.setProjectAnalyzeId(projectAnalyzeId);
            affectCount = projectAnalyzeDao.insert(analyze);
        }

        return affectCount;
    }
    
    private int updateAnalyzeItem(String projectAnalyzeId, String projectTypeId, String userId, HttpServletRequest request) {
        int freeCount = 0;
        int chargeCount = 0;
        List<AnalyzeItemVO> analyzeItemList = analyzeItemDao.queryListByTypeId(projectTypeId, projectAnalyzeId);
        
        for (AnalyzeItemVO analyzeItem : analyzeItemList) {

            String analyzeDetail = request.getParameter("analyzeDetail_" + analyzeItem.getItemIndex());
            String rechageFee = request.getParameter("rechageFee_" + analyzeItem.getItemIndex());
            
            if (StringUtils.isNotBlank(analyzeDetail)) {
                analyzeItem.setAnalyzeDetail(analyzeDetail);
                analyzeItem.setRechageFee(new BigDecimal(rechageFee == null ? "0" : rechageFee));
                if (StringUtils.isBlank(analyzeItem.getAnalyzeItemId())) {
                    analyzeItem.setAnalyzeItemId(UUID.randomUUID().toString());
                    analyzeItem.setProjectAnalyzeId(projectAnalyzeId);
                    analyzeItem.setPublishUser(userId);
                    analyzeItem.setDataStatus(0);
                }
            }
        }
        
        analyzeItemDao.delete(projectAnalyzeId);
        
        for (AnalyzeItemVO analyzeItem : analyzeItemList) {
            if (StringUtils.isNotBlank(analyzeItem.getAnalyzeItemId())) {
                analyzeItemDao.insert(analyzeItem);
                if (analyzeItem.getRechageFee().doubleValue() > 0) {
                    chargeCount = chargeCount + 1;
                } else {
                    freeCount = freeCount + 1;
                }
            }
        }
        // 1，免费；2，部分免费；3，收费；4，未更新记录
        if (freeCount > 0 && chargeCount == 0) {
            return 1;
        } else if (freeCount > 0 && chargeCount > 0) {
            return 2;
        } else if (freeCount == 0 && chargeCount > 0) {
            return 3;
        } else {
            return 4;
        }
        
    }
    
    /**
     * 根据ID获取拆解报告实体
     *
     * @param id 主键
     * @return 拆解报告信息
     */
    public ProjectAnalyzeVO findById(String id) {
        return projectAnalyzeDao.findById(id);
    }
    
    /**
     * 根据ID获取拆解报告实体
     *
     * @param id 主键
     * @return 拆解报告信息
     */
    public List<AnalyzeItemVO> findItemById(String id, String userId) {
        return analyzeItemDao.queryList(id, userId);
    }
    
    /**
     * 按查询条件【分页】查询
     *
     * @param param 拆解报告查询条件
     * @return 拆解报告列表
     */
    public List<ProjectAnalyzeVO> queryByPage(ProjectAnalyzeParam param) {
        return projectAnalyzeDao.queryByPage(param);
    }
    
    /**
     * 根据ID删除拆解报告
     *
     * @param id 主键
     */
    @Transactional
    public Integer delete(String id) {
        analyzeItemDao.delete(id);
        return projectAnalyzeDao.delete(id);
    }

    /**
     * 查询拆解数据
     *
     * @return
     */
    public List<Map<String, Object>> queryAnalyzeDataList() {
        return projectAnalyzeDao.queryAnalyzeDataList();
    }
}
